<script lang="ts" setup>
import type { RouteLocationMatched } from "vue-router"
import { useRouteListener } from "@@/composables/useRouteListener"
import { compile } from "path-to-regexp"

const route = useRoute()

const router = useRouter()

const { listenerRouteChange } = useRouteListener()

/** 定义响应式数据 breadcrumbs，用于存储面包屑导航信息 */
const breadcrumbs = ref<RouteLocationMatched[]>([])

/** 获取面包屑导航信息 */
function getBreadcrumb() {
  breadcrumbs.value = route.matched.filter(item => item.meta?.title && item.meta?.breadcrumb !== false)
}

/** 编译路由路径 */
function pathCompile(path: string) {
  const toPath = compile(path)
  return toPath(route.params)
}

/** 处理面包屑导航点击事件 */
function handleLink(item: RouteLocationMatched) {
  const { redirect, path } = item
  if (redirect) return router.push(redirect as string)
  router.push(pathCompile(path))
}

// 监听路由变化，更新面包屑导航信息
listenerRouteChange((route) => {
  if (route.path.startsWith("/redirect/")) return
  getBreadcrumb()
}, true)
</script>

<template>
  <el-breadcrumb>
    <el-breadcrumb-item v-for="(item, index) in breadcrumbs" :key="item.path">
      <span v-if="item.redirect === 'noRedirect' || index === breadcrumbs.length - 1" class="no-redirect">
        <span class="title">{{ item.meta.title }}</span>
        <span class="desc">{{ item.meta.desc }}</span>
      </span>
      <a v-else @click.prevent="handleLink(item)" class="no-redirect">
        <span>{{ item.meta.title }}</span>
        <span>{{ item.meta.desc }}</span>
      </a>
    </el-breadcrumb-item>
  </el-breadcrumb>
</template>

<style lang="scss" scoped>
@import "@@/styles/variables.scss";

.el-breadcrumb {
  line-height: var(--v3-navigationbar-height);
  margin-left: 10px;
  .el-breadcrumb__item {
    height: 100%;
  }
  .no-redirect {
    color: var(--v3-navigationbar-text-color); /* 跟随导航栏主题的文字颜色 */
    display: flex;
    flex-direction: column;
    gap: 10px;
    span {
      height: 50%;
      line-height: 100%;
    }
  }
  a {
    font-weight: normal;
  }
}
.title {
  font-size: 16px;
  font-weight: 500;
}
.desc {
  font-size: 12px;
}
::deep(.el-breadcrumb__inner) {
  height: 100%;
}
</style>
